package com.studerb.gnusbin;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.support.AbstractApplicationContext;

import com.studerb.events.ShutdownEvent;

public class ShutdownEventListener implements ApplicationListener, ApplicationContextAware {
	private AbstractApplicationContext appContext;
	private Logger logger = Logger.getLogger(ShutdownEventListener.class);
	
	@Override public void onApplicationEvent(ApplicationEvent event) {
		if (event instanceof ShutdownEvent) {
			logger.debug("received shutdown event from: " + event);
			logger.debug("Shutting down Spring Context.");
			this.appContext.close();
			logger.debug("Shutting down JVM.");
			System.exit(0);
		}
	}
	@Override public void setApplicationContext(ApplicationContext appContext) throws BeansException {
		this.appContext = (AbstractApplicationContext)appContext;
		}
}
